'工具'
import hashlib
import os
import shutil
import smtplib
import sys
import time
from email.mime.text import MIMEText
from email.utils import formataddr

import config as c

file_max_size = 1  # Mb，日志文件多大保存一次
# 可以保证在任何路径运行，都获取到正确的路径
os.chdir(sys.path[0])
cache_dir = os.path.abspath(".") + "/cache"
log_dir = os.path.abspath(".") + "/log"


headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}

# ============ time ========

# ============ log =========


def get_day_of_month():
    """
    获取指定的某天是某个月的第几周
    周一为一周的开始
    实现思路：就是计算当天在本年的第y周，本月一1号在本年的第x周，然后求差即可。
    因为查阅python的系统库可以得知：

    """

    end = int(time.strftime("%d"))

    return end

# 生成MD5


def genearte_md5(md5_str):
    """_summary_

    Args:
        md5_str (_type_): _description_

    Returns:
        _type_: _description_
    """
    # 创建md5对象
    hl = hashlib.md5()

    # Tips
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update(md5_str.encode(encoding='utf-8'))

    md5 = hl.hexdigest()

    print('MD5加密前为 ：' + md5_str)
    print('MD5加密后为 ：' + md5)

    return md5


def save_log2(content_, log_file_name, test):
    """_summary_

    Args:
        content_ (_type_): _description_
        log_file_name (_type_): _description_
        test (_type_): _description_
    """
    content = "********************  " + get_time(
    ) + "  ********************" + "    \n" + str(content_) + "\n\n\n"
    if test:
        print(log_file_name + "\n" + content)
    else:
        save_log(content, log_file_name)


def save_log(content, log_file_name):
    """_summary_

    Args:
        content (_type_): _description_
        log_file_name (_type_): _description_
    """
    os.makedirs(log_dir, exist_ok=True)

    log_file = log_dir + "/" + log_file_name

    # 每次获取现在的ip，都把文件中的上次ip更新一下
    with open(log_file, 'a') as file:
        file.write(content)

    file_size(log_file)


# M
def file_size(log_file):
    """文件大小

    Args:
        log_file (_type_): _description_

    Returns:
        _type_: _description_
    """
    log_name = os.path.split(log_file)[1].replace(".log", "")
    ip_cache_dir_ = cache_dir + "/" + log_name

    os.makedirs(ip_cache_dir_, exist_ok=True)

    fsize = os.path.getsize(log_file) / float(1024 * 1024)

    if fsize > file_max_size:
        shutil.move(log_file, ip_cache_dir_ + "/" + get_time() + ".log")
    return fsize


def get_time():
    """_summary_

    Returns:
        _type_: _description_
    """
    return time.strftime('%Y_%m_%d-%H_%M_%S', time.localtime(time.time()))


def send_mail(subject,
              content,
              mail_from_usr,
              mail_from_usr_pw,
              receivers: list,
              cc_recipients=None,
              smtp_server="smtp.qq.com",
              smtp_port=465,
              sender_name="管理员"):
    """发邮件

    Args:
        subject (_type_): _description_
        content (_type_): _description_
        mail_from_usr (_type_): 发件人
        mail_from_usr_pw (_type_): _description_
        receivers (list): 接收人
        cc_recipients (list, optional): 抄送给谁. Defaults to None.
        smtp_server (str, optional): _description_. Defaults to "smtp.qq.com".
        smtp_port (int, optional): _description_. Defaults to 465.
        limit_sec (int, optional): _description_. Defaults to 60.
        sender_name (str, optional): 发件人名字. Defaults to "集群管理员".

    Returns:
        _type_: _description_
    """
    if cc_recipients is None:
        cc_recipients = []

    all_recipients = receivers + cc_recipients

    # 生成一个MIMEText对象（还有一些其它参数）
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = formataddr((sender_name, mail_from_usr))
    msg["To"] = ", ".join(receivers)
    msg["Cc"] = ", ".join(cc_recipients)

    try:
        # 通过ssl方式发送，服务器地址，端口
        s = smtplib.SMTP_SSL(smtp_server, smtp_port)
        # 登录到邮箱
        s.login(mail_from_usr, mail_from_usr_pw)
        # 发送邮件：发送方，收件方，要发送的消息
        s.sendmail(mail_from_usr, all_recipients, msg.as_string())
        s.quit()

        return True
    except Exception as e:  # pylint: disable=w0718
        print(e)
    return False


def send_mails(subject, content):
    """使用163邮箱发邮件，内置账号

    Args:
        subject (_type_): _description_
        content (_type_): _description_
    """

    send_mail(subject, content, c.MAIL_FROM_USER, c.MAIL_FROM_USER_PW,
              c.MAIL_TO_USERS[0:1], c.MAIL_TO_USERS[1:], c.MAIL_SMTP_SERVER)
